package dao

import (
	"SelectCourse/types"
	"github.com/jinzhu/gorm"
)

func GetTeacherCourse(teacherId string) []*types.TCourse {
	var result []types.TCourse
	Db.Table("tcourse").Where("TeacherID = ?", teacherId).Find(&result)

	var result2 []*types.TCourse
	for i := 0; i < len(result); i++ {
		result2 = append(result2, &result[i])
	}

	return result2
}

func GetStudentCourse(studentId string) []types.TCourse {
	var result []types.TCourse
	Db.Table("tcourse").
		Joins("left join `studentcourse` on studentcourse.courseid = tcourse.id").
		Select("tcourse.id, tcourse.coursename, tcourse.capacity, tcourse.TeacherID").
		Where("userid = ?", studentId).Find(&result)
	return result
}

func GetStudentCourseWithTx(studentId string, tx *gorm.DB) ([]types.TCourse, error) {
	var result []types.TCourse
	err := tx.Table("tcourse").
		Joins("left join `studentcourse` on studentcourse.courseid = tcourse.id").
		Select("tcourse.id, tcourse.coursename, tcourse.capacity, tcourse.TeacherID").
		Where("userid = ?", studentId).Find(&result).Error
	return result, err
}

func GetCoursesCapacityWithTx(courseId string, tx *gorm.DB) ([]types.TCourse, error) {
	var courses []types.TCourse
	err := tx.Table("tcourse").Select("capacity").Where("id = ?", courseId).First(&courses).Error
	return courses, err
}

func UpdateCourseCapWithTx(courseId string, cap int, tx *gorm.DB) error {
	return tx.Table("tcourse").Where("id = ?", courseId).Update("capacity", cap).Error
}

func InsertStudentCourseWithTx(studentId string, courseId string, tx *gorm.DB) error {
	var studentCourse types.StudentUserCourse
	studentCourse.UserID = studentId
	studentCourse.CourseID = courseId
	return tx.Table("studentcourse").Create(studentCourse).Error
}

func UpdateStudentCourseWithTx(studentId string, courseId string, tx *gorm.DB) error {
	var studentCourse types.StudentUserCourse
	studentCourse.UserID = studentId
	studentCourse.CourseID = courseId
	return tx.Table("studentcourse").Where("userid = ?", studentId).Update("courseid", courseId).Error
}
